package com.yisu.expressway.ewf.common.getui;

import com.alibaba.fastjson.JSON;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.base.uitls.AppConditions;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.APNTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.qiniu.util.Json;
import com.yisu.expressway.ewf.common.mq.MessageQueueAPI;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016-12-07.
 */
public class GeTuiAPI {
    private static String appId = "XiNYHv9sIB9yDGZM38bSe3";
    private static String appKey = "nRdQ3Y2r94A7ixCrjK1iz9";
    //AppID：XiNYHv9sIB9yDGZM38bSe3  AppKey：nRdQ3Y2r94A7ixCrjK1iz9
    //AppSecret：rx7Penlboq8di1Oc6sEpe8    MasterSecret：3KIWI9YpaG6tUnDRCAhLG9
    private static String masterSecret = "3KIWI9YpaG6tUnDRCAhLG9";
    private static String url = "http://sdk.open.api.igexin.com/apiex.htm";

    public static void main(String[] args) throws Exception {
        //pushAPNMessageToSingle("krGsnKzZlO7outeUA7YTb8", "4cb0495f73fab55b3f100b87b1d212e982f5270d0d5b1f6b28008b7c50a42a30", "aaa", "aaaa");
        //pushMessageToSingleWithAndroid("eae85cfa2026eefe963bc59aa52cf5c9","aaa","aaa",1);
        pushMessageToSingleWithAndroid("eae85cfa2026eefe963bc59aa52cf5c9", "aaa", "aaa", 2, "aaa");
        //pushMessageToApp();
    }

    public static boolean pushMessageToSingle(String cid, Integer deviceType, String title, String content, Integer pushType, String transmissionContent) {
        try {
            if (deviceType == 1) {
                if (pushType == 1) {
                    pushAPNMessageToSingle(appId, cid, title, content, 1, transmissionContent);
                    pushAPNMessageToSingle(appId, cid, title, content, 2, transmissionContent);
                } else {
                    return pushAPNMessageToSingle(appId, cid, title, content, 2, transmissionContent);
                }
            } else {
                if (pushType == 1) {
                    pushMessageToSingleWithAndroid(cid, title, content, 2, transmissionContent);
                    pushMessageToSingleWithAndroid(cid, title, content, 1, transmissionContent);
                } else {
                    pushMessageToSingleWithAndroid(cid, title, content, 2, transmissionContent);
                }
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private static boolean pushMessageToSingleWithAndroid(String cid, String title, String content, Integer pushType, String transmissionContent) {
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        if (pushType == 1) {
            NotificationTemplate template = notificationTemplateModel(title, content, transmissionContent);
            message.setData(template);
        } else {
            TransmissionTemplate template = transmissionTemplateModel(transmissionContent);
            message.setData(template);
        }
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
        if (ret.getResponse().get("result").equals("ok")) {
            return true;
        } else {
            return false;
        }
    }

    private static boolean pushAPNMessageToSingle(String appId, String cid, String title, String content, Integer pushType, String transmissionContent) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent(transmissionContent);
        template.setTransmissionType(2);
        if (pushType == 1) {
            APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
            alertMsg.setBody(content);
            // IOS8.2以上版本支持
            alertMsg.setTitle(title);
            APNPayload payload = new APNPayload();
            //在已有数字基础上加1显示，设置为-1时，在已有数字上减1显示，设置为数字时，显示指定数字
            payload.setAutoBadge("+1");
            payload.setContentAvailable(1);
            payload.setSound("default");
            payload.setCategory("$由客户端定义");
            //简单模式APNPayload.SimpleMsg
            payload.setAlertMsg(new APNPayload.SimpleAlertMsg("hello"));
            //字典模式使用下者
            //payload.setAlertMsg(getDictionaryAlertMsg());
            template.setAPNInfo(payload);
        }
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(cid);
        //target.setAlias(Alias);
        IPushResult ret = null;

        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
        if (ret.getResponse().get("result").equals("ok")) {
            return true;
        } else {
            return false;
        }
















        /*
        IGtPush push = new IGtPush(url, appKey, masterSecret);
        APNTemplate t = new APNTemplate();
        APNPayload apnpayload = new APNPayload();
        apnpayload.setSound("");
        //apn高级推送
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        ////通知文本消息标题
        alertMsg.setTitle(title);
        //通知文本消息字符串
        alertMsg.setBody(content);
        //对于标题指定执行按钮所使用的Localizable.strings,仅支持IOS8.2以上版本
        //alertMsg.setTitleLocKey("ccccc");
        //指定执行按钮所使用的Localizable.strings
        //alertMsg.setActionLocKey("ddddd");
        apnpayload.setAlertMsg(alertMsg);

        t.setAPNInfo(apnpayload);
        SingleMessage sm = new SingleMessage();
        sm.setData(t);
        //target.setAlias(Alias);
        IPushResult ret = null;
        //System.out.println("11111");
        try {
            ret = push.pushAPNMessageToSingle(appId, cid, sm);
        } catch (RequestException e) {
            e.printStackTrace();
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
        if (ret.getResponse().get("result").equals("ok")) {
            return true;
        } else {
            return false;
        }*/
    }

    private static void pushMessageToApp() {
        IGtPush push = new IGtPush(url, appKey, masterSecret);

        NotificationTemplate template = notificationTemplateModel("a", "b", "bbb");
        AppMessage message = new AppMessage();
        message.setData(template);

        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);
        //推送给App的目标用户需要满足的条件
        AppConditions cdt = new AppConditions();
        List<String> appIdList = new ArrayList<String>();
        appIdList.add(appId);
        message.setAppIdList(appIdList);
        //手机类型
        List<String> phoneTypeList = new ArrayList<String>();
        //省份
        List<String> provinceList = new ArrayList<String>();
        //provinceList.add("浙江");
        //自定义tag
        List<String> tagList = new ArrayList<String>();
        tagList.add("13231231");

        //cdt.addCondition(AppConditions.PHONE_TYPE, phoneTypeList);
        //cdt.addCondition(AppConditions.REGION, provinceList);
        cdt.addCondition(AppConditions.TAG, tagList);
        message.setConditions(cdt);

        IPushResult ret = push.pushMessageToApp(message, "任务别名_toApp");
        System.out.println(ret.getResponse().toString());
    }

    /**
     * 通知栏推送
     *
     * @param title
     * @param content
     * @return
     */
    public static NotificationTemplate notificationTemplateModel(String title, String content, String transmissionContent) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 设置通知栏标题与内容
        template.setTitle(title);
        template.setText(content);
        // 配置通知栏图标
        template.setLogo("icon.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(1);
        template.setTransmissionContent(transmissionContent);
        return template;
    }

    /**
     * 透传推送
     *
     * @return
     */
    public static TransmissionTemplate transmissionTemplateModel(String transmissionContent) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent(transmissionContent);
        // 设置定时展示时间
        // template.setDuration("2015-01-16 11:40:00", "2015-01-16 12:24:00");
        return template;
    }

    @Resource
    private static MessageQueueAPI messageQueueAPI;

    private static String messageMqGroupName = "";
    private static String mqIp = "";
    private static String topic = "";
    private static String tag = "";

    public static void pushMessageToSingleWithMq(String userId, String title, String content) throws MQClientException,
            InterruptedException {
        GeTuiInfoModel geTuiInfoModel = new GeTuiInfoModel();
        geTuiInfoModel.setContent(content);
        geTuiInfoModel.setUserId(userId);
        geTuiInfoModel.setTitle(title);
        String message = JSON.toJSONString(geTuiInfoModel);
        messageQueueAPI.SetMessage(messageMqGroupName, mqIp, topic, tag, message);
    }
}